var express = require('express');
var router = express.Router();
var core = require('core');
var wechat = core.wechat;
var util = core.util;
var crypto = require('crypto');
var xml2js = require('xml2js');
var Event = wechat.Event;
var eventReg = require('./event')();
var pay = require('./pay');

var rWechat = function(req, res, next){
    var query = req.query;
    //验证微信服务器
    var sign = function(options){
        var sha1 = crypto.createHash('sha1');
        var signature = util.sort.value([wechat.config.token, query.timestamp, query.nonce]).join('');
        sha1.update(signature);
        signature = sha1.digest('hex');

        if(query.signature === signature)
            return options.success();
        else
            return options.error();
    };

    //判断是否为微信的事件推送
    var methodType = req.method === "POST" ? 1 : 0;

    if(methodType){
        //事件推送的话就先验证是否为微信服务器发送的请求，如果是则开始解析xml，反之告知微信服务器验证失败
        sign({
            success : function(){
                var xml = "";
                req.on('data', function(data){
                    xml += data;
                });
                req.on('end', function(){
                    //将微信传输的数据解析成json并派发给相对应的事件
                    var xmlParser = new xml2js.Parser({explicitArray : false, ignoreAttrs : true});
                    xmlParser.parseString(xml, function(err, json){
                        if(err){
                            res.send("");
                        };
                        Event.call(json.xml, function(EventRes){
                            EventRes = EventRes || "";
                            //根据派发的事件做出的事件回应
                            if(EventRes){
                                res.set('Content-Type', 'text/xml');
                                EventRes = { xml : EventRes };
                                var builder = new xml2js.Builder();
                                EventRes = builder.buildObject(EventRes);
                            };
                            return res.send(EventRes);
                        });
                    });
                });
            },
            error : function(){
                var err = new Error("微信公众平台验证失败");
                err.status = 999;
                res.send("");
            }
        });
    }else
        sign({
            success : function(){
                return res.send(query.echostr);
            },
            error : function(){
                var err = new Error("微信公众平台验证失败");
                err.status = 999;
                next(err);
            }
        });
};

router.get('/', rWechat);
router.get('/index', rWechat);
router.get('/pay', pay.get);
router.post('/', rWechat);
router.post('/index', rWechat);
router.post('/pay', pay.post);
router.post('/pay/note', pay.node);
// router.get('/MP_verify_BhCzKCxnF7nw4AhQ.txt', function(req,res,next){
//     res.send('BhCzKCxnF7nw4AhQ');
// });
// router.get('/admin/MP_verify_BhCzKCxnF7nw4AhQ.txt', function(req,res,next){
//     res.send('BhCzKCxnF7nw4AhQ');
// });
// router.get('/open/MP_verify_BhCzKCxnF7nw4AhQ.txt', function(req,res,next){
//     res.send('BhCzKCxnF7nw4AhQ');
// });

// router.get('/pay/MP_verify_8vDF2l164kRpiYeG.txt', function(req,res,next){
    // res.send('8vDF2l164kRpiYeG');
// });

module.exports = router;
